package com.qfedu.knowledge.factory;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.qfedu.knowledge.entity.bo.FileInfoBO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @ClassName FileFactory
 * @Author ykx
 * @Date 2024/5/3 12:59
 * @Version 1.0
 */
@Component
public class FileFactory extends AbstractFactory {

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer webServer;// 获取存储服务器的请求URL 对应配置文件中的 web-server-url


    @Override
    public FileInfoBO create() {
        return new FileInfoBO();
    }

    @Override
    public FileInfoBO create(MultipartFile multipartFile) throws IOException {
        FileInfoBO fileInfoBO = this.create();
        // 获取文件名及后缀
        String originalFilename = multipartFile.getOriginalFilename() == null ? "" : multipartFile.getOriginalFilename(); // 上传的文件名称
        fileInfoBO.setName(originalFilename);
        String fileExtName = originalFilename.substring(originalFilename.indexOf('.') + 1);// 获取文件后缀名
        fileInfoBO.setSuffix(fileExtName);

        fileInfoBO.setSize(multipartFile.getSize());
        // 将文件存储到图片服务器上
        StorePath storePath = storageClient.uploadFile(multipartFile.getInputStream(), multipartFile.getSize(), fileExtName, null);
        fileInfoBO.setUrl(webServer.getWebServerUrl() + storePath.getFullPath());
        fileInfoBO.setDeleteUrl(storePath.getFullPath());
        fileInfoBO.setDownloadUrl(storePath.getFullPath());

        return fileInfoBO;
    }
}
